import React, { useEffect, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { StoreDispatch, TabItem,ReducerType } from '../../utils/Type'
import { getTabs} from '../../store/action'
import { Grid, Image, Sidebar } from 'react-vant';

type Props = {}

const Classify = (props: Props) => {
  const dispatch: StoreDispatch = useDispatch()
  useEffect(() => {
    dispatch(getTabs())
  }, [dispatch])
  //定义设置数据
  const tabs = useSelector((state: ReducerType) => state.tabs)
  const [active, setActive] = useState(0);
  const [isLodaing, setLoading] = useState(false);
  return (
    <div className='classify'>
      {/* 左 */}
      <div className='classify-left'>
        <Sidebar value={active} onChange={(index) => {
          setLoading(true)//开启滚动
          setActive(index)//设置下标
          const els = document.querySelectorAll('.tab_item')
          els[index].scrollIntoView({ behavior: 'smooth' })//滚动
          setTimeout(() => {
            setLoading(false)//关闭滚动
          }, 1000);
        }}>
          {
            tabs.map((item: TabItem) => {
              return <Sidebar.Item key={item.id} title={item.title} />
            })
          }
        </Sidebar>
      </div>

      {/* 右 */}
      <div className='classify-right' onScroll={(e: any) => {
        if (isLodaing) {
          return
        }
        const els = document.querySelectorAll('.tab_item')
        els.forEach((item: any, index: number) => {
          if (e.target.scrollTop >= item.offsetTop-50) {//计算是否大于等于顶部距离
            setActive(index)//设置下标进行高亮
          }
        })
      }}>
        {
          tabs.length
            ? tabs.map((item: TabItem) => {
              return <div key={item.id} className="tab_item">
                <h3>{item.title}</h3>
                 {/* @ts-ignore */}
                <Grid columnNum={2}>
                  {
                    item.conList?.length
                      ? item.conList.map((conItem: TabItem) => {
                        return <Grid.Item key={conItem.id}>
                          <Image src={item.img} width="60px" height="60px" />
                          {conItem.title}
                        </Grid.Item>
                      })
                      : '暂无内容'
                  }
                </Grid>
              </div>
            })
            : '暂无数据'
        }
      </div>
    </div>
  )
}

export default Classify